// import BUTILS from "../../@smartcity/universal-utils-browser";
import BUTILS from "../../universal-utils-browser";
import { createEmpty, extend } from "ol/extent";
import * as Layer from "ol/layer";
import * as Source from "ol/source";
import {
  queryExtentByCoordinates,
  queryExtentByFeatures,
  queryExtentByQuery,
} from "./extent";
import * as keys from "./keys";
import { log } from "./log";
import { RenderImageLayerOptions } from "./types";
import { getMap } from "./instance";

/**
 * @description: 渲染图片图层
 * @private
 * @param {RenderImageLayerOptions} options 配置项
 * @returns {Layer.Image<Source.ImageStatic>}
 */
export const renderImageLayer = (
  options: RenderImageLayerOptions
): Layer.Image<Source.ImageStatic> => {
  const mapInstance = getMap();
  if (!mapInstance) {
    throw new Error("地图实例未初始化");
  }

  const {
    coordinates,
    features,
    imageExtent,
    query,
    type: layerType,
    url,
    visible = true,
  } = options;

  let extent = createEmpty();
  if (coordinates) {
    extent = queryExtentByCoordinates(coordinates);
  } else if (features) {
    extent = queryExtentByFeatures(features);
  } else if (query) {
    extent = queryExtentByQuery(query);
  } else if (imageExtent) {
    extent = extend(extent, imageExtent);
  }

  let layer = mapInstance
    .getAllLayers()
    .find((item) => item.get(keys.LAYER_TYPE_KEY) === layerType) as
    | Layer.Image<Source.ImageStatic>
    | undefined;
  if (!(layer instanceof Layer.Image)) {
    layer = new Layer.Image({
      ...BUTILS.Object.excludeProperties(options, [
        "coordinates",
        "features",
        "imageExtent",
        "query",
        "type",
        "url",
      ]),
    });
    layer.set(keys.LAYER_TYPE_KEY, layerType);
    mapInstance.addLayer(layer);
  }

  log("Render Image Layer", options);

  layer.setSource(
    new Source.ImageStatic({
      imageExtent: extent,
      url,
    })
  );
  layer.setVisible(visible);

  return layer;
};

/**
 * @description: 渲染图片图层
 * @private
 * @param {RenderImageLayerOptions} options 配置项
 * @returns {Layer.Image<Source.ImageStatic>}
 */
export const showOrRenderImageLayer = (
  options: RenderImageLayerOptions
): Layer.Image<Source.ImageStatic> => {
  const mapInstance = getMap();
  if (!mapInstance) {
    throw new Error("地图实例未初始化");
  }

  const { type: layerType, visible = true } = options;

  const layer = mapInstance
    .getAllLayers()
    .find((item) => item.get(keys.LAYER_TYPE_KEY) === layerType) as
    | Layer.Image<Source.ImageStatic>
    | undefined;
  if (layer instanceof Layer.Image) {
    log("Change Image Layer Visible", options);
    layer.setVisible(visible);
    return layer;
  }

  return renderImageLayer(options);
};
